package com.zjt.smart.mvp.view;

import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载完成后发起网络请求,每次请求先加载缓存，再加载网络
 */

public class ExtraLoadView<DataType> implements LoadView<DataType> {
    private List<DataType> successData;
    private LoadView<DataType> loadView;
    private List<ExtraLoader> list;

    public ExtraLoadView(LoadView<DataType> loadView) {
        this.loadView = loadView;
        list = new ArrayList<>();
    }

    public void addLoader(ExtraLoader loader) {
        list.add(loader);
    }

    @Nullable
    @Override
    public void onSuccess(List<DataType> data) {
        if (loadView != null) {
            loadView.onSuccess(data);
        }
        successData = data;
        loadExtra();
    }

    @Override
    public void onCache(long cacheTime, List<DataType> data) {
        if (loadView != null) {
            loadView.onCache(cacheTime, data);
        }
        if (data != null && data.size() > 0) {
            successData = data;
            loadExtra();
        }
    }

    @Override
    public void onFail(int errorCode, String errorMsg) {
        if (loadView != null) {
            loadView.onFail(errorCode, errorMsg);
        }
    }

    private void loadExtra() {
        for (ExtraLoader loader : list) {
            executeLoader(loader, true);
            executeLoader(loader, false);
        }
    }

    private void executeLoader(ExtraLoader loader, boolean fromCache) {
        LoadView<Object> extraLoadView = new LoadView<Object>() {
            @Nullable
            @Override
            public void onSuccess(List<Object> data) {
                loader.handleExtraData(successData, data, false);
            }

            @Override
            public void onCache(long cacheTime, List<Object> data) {
                if (data == null) {
                    return;
                }
                loader.handleExtraData(successData, data, true);
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                loader.onExtraFail(errorCode, errorMsg);
            }
        };
        loader.loadExtra(successData, extraLoadView, fromCache);
    }

    public interface ExtraLoader<DataType, ExtraType> extends Loader {

        void loadExtra(List<DataType> data, LoadView<ExtraType> loadView, boolean fromCache);

        void handleExtraData(List<DataType> data, List<ExtraType> extra, boolean fromCache);

        void onExtraFail(int errorCode, String errorMsg);
    }


}
